<template>
  <div class="container-directorys">
    <el-card>
      <!-- 面包屑 有路由参数id和name就显示面包屑,否则就删除-->
      <el-breadcrumb separator-class="el-icon-arrow-right" v-if="subjects.id && subjects.name">
        <el-breadcrumb-item>学科管理</el-breadcrumb-item>
        <el-breadcrumb-item>{{subjects.id ? subjects.name :''}}</el-breadcrumb-item>
        <el-breadcrumb-item>目录管理</el-breadcrumb-item>
      </el-breadcrumb>
      <!-- 筛选 -->
      <el-row>
        <!-- 表单 -->
        <el-col :span="18">
          <!-- form表单 -->
          <el-form inline size="small" >
            <!-- 目录名称输入框 -->
            <el-form-item label="目录名称">
              <el-input v-model="dataParams.directoryName"></el-input>
            </el-form-item>
            <!-- 状态下拉框 -->
            <el-form-item label="状态" style="margin-left: 30px">
              <el-select v-model="dataParams.state" placeholder="请选择">
                <!-- 选择项 -->
                <el-option label="启用" :value="1"></el-option>
                <el-option label="禁用" :value="0"></el-option>
              </el-select>
            </el-form-item>
            <!-- 清除/搜索按钮 -->
            <el-form-item>
              <el-button size="small" @click="resetInput">清除</el-button>
              <!-- 点击搜索重新获取数据 -->
              <el-button size="small" type="primary" @click="getDirList">搜索</el-button>
            </el-form-item>
          </el-form>
        </el-col>
        <!-- 右侧按钮 -->
         <el-col :span="6">
          <el-button class="colright" type="success" icon="el-icon-edit" size="small" @click="showAddDialog = true">新增目录</el-button>
          <el-button class="colright" v-if="subjects.id && subjects.name" type="text" icon="el-icon-back" @click="$router.back()">返回学科</el-button>
        </el-col>
      </el-row>
      <!-- 总计 -->
      <el-alert :title="`数据一共 ${counts} 条`" type="info" show-icon :closable="false" style="margin-bottom:15px"></el-alert>
      <!-- 表格 -->
      <el-table :data="dirList" style="width: 100%;">
        <el-table-column type="index" label="序号"></el-table-column>
        <el-table-column prop="subjectName" label="所属学科"></el-table-column>
        <el-table-column prop="directoryName" label="目录名称"></el-table-column>
        <el-table-column prop="username" label="创建者"></el-table-column>
        <el-table-column prop="addDate" label="创建日期"></el-table-column>
        <el-table-column prop="totals" label="面试题数量"></el-table-column>
        <el-table-column prop="state" label="状态">
          <template slot-scope="scope">
            {{ scope.row.state === 1 ? '已启用' : '已禁用' }}
          </template>
        </el-table-column>
        <el-table-column prop="address" label="操作">
          <template slot-scope="scope">
            <!-- 插槽,当状态status为1时禁用修改/删除按钮 -->
            <el-button type="text" @click="editState(scope.row)">{{ scope.row.state === 1 ? '禁用' : '启用' }}</el-button>
            <el-button type="text" @click="editDirectorys(scope.row)" :disabled="scope.row.state === 1">修改</el-button>
            <el-button type="text" @click="removeDir(scope.row)" :disabled="scope.row.state === 1">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
      <!-- 分页 -->
      <el-pagination
        style="float: right; margin: 20px"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="dataParams.page"
        :page-sizes="[10, 20, 30, 50]"
        :page-size="100"
        background
        layout="prev, pager, next, sizes, jumper"
        :total="counts"
      ></el-pagination>
    </el-card>
    <!-- 新增目录弹层 子组件 -->
    <DirectorysAdd
    :showAddDialog.sync="showAddDialog"
    :subjects="subjects"
    :addFrom="addFrom"/>
    <!-- 修改目录弹层 -->
    <el-dialog title="修改目录" :visible.sync="showEditDialog" width="40%" @close="btnCancel">
      <el-form :model="editDirectoryList" :rules="directorysFormRules" ref="directorysFormRef" label-width="80px">
        <el-form-item v-if="!subjects.id && !subjects.name" label="所属学科"  prop="value">
          <el-select v-model="editDirectoryList.value" placeholder="请选择" style="width: 100%;">
            <el-option :label="item.label" :value="item.value" v-for="item in addFrom" :key="item.value"> </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="目录名称" prop="directoryName">
          <el-input v-model="editDirectoryList.directoryName" placeholder="请输入目录名称"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer">
        <el-button @click="btnCancel">取消</el-button>
        <el-button type="primary" @click="btnOk">确定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
// 引入api接口方法
import { list, changeState, update, remove } from '@/api/hmmm/directorys'
import { simple } from '@/api/hmmm/subjects'
// 引入格式化日期时间的过滤器方法
import { parseTimeByString } from '@/filters/index'
// 引入子组件
import DirectorysAdd from '../components/directorys-add.vue'
export default {
  name: 'Directorys',
  data () {
    return {
      // v-model双向数据绑定,请求参数
      dataParams: {
        page: 1, // 当前页码
        pagesize: 10, // 页尺寸,每页显示数量
        directoryName: '', // 目录名称
        state: null // 状态 1 启用 0 禁用
      },
      // 验证校验规则
      directorysFormRules: {
        directoryName: [{ required: true, message: '请输入目录名称', trigger: 'blur' }],
        value: [{ required: true, message: '请选择所属学科', trigger: 'change' }]
      },
      // 添加目录的数据
      directorysForm: {
        directoryName: '', // 目录名称
        value: ''// 下拉框的值
      },
      // 目录数据列表
      dirList: [],
      // 返回数据总数量
      counts: 0,
      showAddDialog: false, // 新增目录 弹层的显示与隐藏
      showEditDialog: false, // 修改目录 弹层的显示与隐藏
      addFrom: [], // 简单学科数据列表
      // 数据id'
      infoId: '',
      // 修改请求数据
      editDirectoryList: {
        directoryName: '',
        value: ''
      }
    }
  },
  components: { DirectorysAdd },
  // 计算属性
  computed: {
    // 获取路由传参的query参数
    subjects () {
      return this.$route.query || null
    }
  },
  // 侦听地址栏数据
  watch: {
    // 当url地址发生变化时,重新加载数据,也就是当在点击学科进入目录管理时,重新获取对应id数据
    '$route.query' () {
      this.getDirList()
    }
  },
  created () {
    this.getDirList() // 获取目录列表数据方法
    this.getSubjectsList() // 获取学科简单数据方法
  },
  methods: {
    // 点击 '清除'按钮,重置输入框内容
    resetInput () {
      // 清空输入框
      this.dataParams.directoryName = ''
      // 重置下拉框
      this.dataParams.state = null
      // 重新加载数据
      this.getDirList()
    },
    // 获取目录列表数据
    async getDirList () {
      try {
        // 添加subjectID属性
        this.dataParams.subjectID = this.subjects.id || null
        const { data } = await list(this.dataParams)
        // console.log(data)
        // 格式化日期
        data.items.forEach(item => {
          item.addDate = parseTimeByString(item.addDate)
        })
        // 赋值
        this.dirList = data.items
        this.counts = data.counts
        // console.log(this.$route.query)
      } catch (error) {
        this.$message.error('请求目录列表数据失败！')
      }
    },
    // 获取简单学科列表数据
    async getSubjectsList () {
      try {
        const { data } = await simple()
        this.addFrom = data
        // console.log('this.addFrom', this.addFrom)
      } catch (error) {
        console.log(error)
      }
    },
    // 重置表单
    restDir () {
      this.$refs.directorysFormRef.resetFields()
      this.directorysForm.value = ''
    },
    // 切换状态
    async editState (row) {
      // row是点击标签时的当前行数据
      // console.log('row', row)
      try {
        await changeState({
          id: row.id,
          state: row.state === 1 ? 0 : 1
        })
        this.$message.success('切换状态成功')
        // 重新渲染
        row.state = row.state === 1 ? 0 : 1
      } catch (error) {
        // console.log(error)
        this.$message.error('操作失败')
      }
    },
    // 点击修改,修改目录
    editDirectorys (row) {
      // console.log('row', row)
      // console.log(row.subjectID)
      // 赋值
      this.editDirectoryList.value = row.subjectID
      this.infoId = row.id
      console.log(row.id)
      this.editDirectoryList.directoryName = row.directoryName
      console.log(row.directoryName)
      this.showEditDialog = true // 弹层开启
    },
    // 点击确定按钮
    async btnOk () {
      // 更新之前 先做手工校验
      await this.$refs.directorysFormRef.validate()
      try {
        // 当有路由query参数时
        if (this.subjects.id && this.subjects.name) {
          await update({
            id: this.infoId,
            subjectID: +this.subjects.id,
            directoryName: this.editDirectoryList.directoryName
          })
          this.$message.success('修改目录成功')
          this.getDirList() // 重新渲染数据
        } else {
        // 当没有路由query参数时
          await update({
            id: this.infoId,
            subjectID: this.editDirectoryList.value,
            directoryName: this.editDirectoryList.directoryName
          })
          this.$message.success('修改目录成功')
          this.getDirList()
        }
      } catch (error) {
        console.log(error)
      }
      this.showEditDialog = false
    },
    // 点击修改目录取消时
    btnCancel () {
      // 重置表单数据
      this.editDirectoryList = {
        directoryName: '',
        value: ''
      }
      this.$refs.directorysFormRef.resetFields() // 重置校验结果
      this.showEditDialog = false
    },
    // 点击删除目录时
    // 删除
    async removeDir (row) {
      try {
        await this.$confirm('此操作将永久删除该目录, 是否继续？', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        })
        await remove(row)
        // 解决当页面只有一条数据时,删除页面后内容为Not Data/空时的bug
        if (this.dirList.length === 1) {
          this.dataParams.page = this.dataParams.page > 1 ? this.dataParams.page - 1 : 1
        }
        this.getDirList()// 重新渲染数据
        this.$message.success('删除成功!')
      } catch (e) {
        console.log(e)
        this.$message.error('删除失败!')
      }
    },
    // 多少页 size-change --> pageSize 改变时会触发 每页条数
    handleSizeChange (pageSize) {
      // console.log('pageSize', pageSize)
      this.dataParams.pagesize = pageSize
      this.getDirList()
    },
    // 每页多少条数据 current-change --> currentPage 改变时会触发
    handleCurrentChange (page) {
      // console.log('page', page)
      this.dataParams.page = page
      this.getDirList()
    }
  }
}
</script>

<style scoped lang='scss'>
.left-fot {
  margin-left: 9px;
}
.el-row {
  margin-top: 20px;
}
.colInput {
  height: 35px;
}
.colright {
  float: right;
  height: 35px;
  margin-left: 10px;
}
.el-breadcrumb {
  padding-bottom: 20px;
  border-bottom: 1px solid #ccc;
}
.inputCol {
  width: 200px;
}

.el-table {
  margin-top: 10px;
}
.el-pagination {
  float: right;
  margin-top: 20px;
}
.elform {
  width: 100%;
}

.el-form-item__content {
  margin-left: 10px;
}
</style>
